import React, { useState, useEffect } from 'react';
import moment from 'moment';
import styles from './index.less';

const yearTemplate = 'YYYY/MM/DD';
const timeTemplate = 'h:mm:ss';
const itemStyle = { paddingRight: 8 };
const weekDays = [ '星期一', '星期二', '星期三', '星期四', '星期五', '星期六','星期天'];

function getCurTimeStr() {
  const now = moment(Date.now());
  let year = now.format(yearTemplate);
  let time = now.format(timeTemplate);
  let weekDay = weekDays[now.weekday()];
  return {
    year,
    time,
    weekDay,
  };
}
const Timer = () => {
  const [time, setTime] = useState(getCurTimeStr());
  useEffect(() => {
    let timeHandler = setInterval(() => {
      setTime(getCurTimeStr());
    }, 1000);
    return () => {
      timeHandler && clearInterval(timeHandler);
    };
  }, []);
  return (
    <span className={styles.time}>
      <div className={styles.timeInner}>
        <div>
          <div className={styles.data} style={itemStyle}>
            {time.time}
          </div>
          <div className={styles.year} style={itemStyle}>
            {time.year}
          </div>
        </div>
        <div className={styles.weekDay} >{time.weekDay} </div>
      </div>
    </span>
  );
};

export default Timer;
